/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 引入 await-to-js 库，用于处理异步操作
const { to } = require('await-to-js')
// 引入 moment 库，用于日期和时间操作
const moment = require('moment')
// 引入 fs 模块，用于文件系统操作
const fs = require('fs')

// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 引入 esm 库，用于在 Node.js 中支持 ES6 模块
const esm = require('esm')
// 使用 esm 配置来加载模块
const requireModule = esm(module)

// 地区
const { region } = requireModule(path.join(__dirname, '../src/utils/modules/settings.js'))

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// front src 目录
const FRONT_SRC_DIR = path.join(ROOT_DIR, 'src')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

// 加载 FOLDER_OPTIONS 常量
const { FOLDER_OPTIONS } = requireModule(path.join(FRONT_SRC_DIR, 'utils/modules/constant.js'))

// 读取并构建 fixedGroupMapObject
const { finalGroupMap, flatGroupMap, groupArray } = requireModule(path.join(HELPERS_DIR, 'readGroup.js'))

// 计算准确统计
const { calcAccuracySummary, ACCURACY_SUMMARY_CN_MAP } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))
const { filterForecaArray } = require(path.join(HELPERS_DIR, 'filterForecaArray.js'))

// 获取幸运号和杀号
const getLuckAndForecastGroupNames = require(path.join(HELPERS_DIR, 'getLuckAndForecastGroupNames.js'))

// 读取所有数据
const { readAllValues } = require(path.join(HELPERS_DIR, 'readAllValues.js'))

const allValues = readAllValues(region)
// .slice(0, 200)
// .slice(0, 500)
// .slice(0, 1000)

// console.log(allValues.length)

const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((num) => (num < 10 ? `0${num}` : `${num}`))

// console.log(allNumbers)
// console.log(flatGroupMap)
fs.writeFileSync(path.join(__dirname, 'json/flatGroupMap.json'), JSON.stringify(flatGroupMap, null, 2), 'utf8')
fs.writeFileSync(path.join(__dirname, 'json/groupArray.json'), JSON.stringify(groupArray, null, 2), 'utf8')

// 初始化目标对象，每个数字对应空对象
const numberGroupMap = allNumbers.reduce((acc, num) => {
  acc[num] = {}
  return acc
}, {})

/*
  {
    "01": {},
    "02": {},
    "03": {},
    "04": {},
    "05": {},
    "06": {},
    "07": {},
    "08": {},
    "09": {}
  }
*/

// fs.writeFileSync(path.join(__dirname, 'json/​Steps-01.json'), JSON.stringify(numberGroupMap, null, 2), 'utf8')

// 初始化每个Number在不同分组中的索引
Object.entries(flatGroupMap).forEach(([groupName, groups]) => {
  // groups是包含两个子数组的数组
  groups.forEach((group, groupIndex) => {
    group.forEach((num) => {
      // 将数字转为两位字符串，如2 -> '02'
      const numStr = num.toString().padStart(2, '0')
      // 确保该数字在映射中存在
      if (numberGroupMap[numStr]) {
        // 将分组名称和子数组索引存入
        numberGroupMap[numStr][groupName] = groupIndex
      }
    })
  })
})

// fs.writeFileSync(path.join(__dirname, 'json/​Steps-02.json'), JSON.stringify(numberGroupMap, null, 2), 'utf8')
/*
  {
    "01": {
      "TWO_ASCENDING_GROUPS": 0,
      "TWO_ODD_EVEN_GROUPS": 0,
      "TWO_PRIME_GROUPS": 7,
      "TWO_MIRROR_GROUPS": 0,
    },
    "02": {},
    "03": {},
    "04": {},
    "05": {},
    "06": {},
    "07": {},
    "08": {},
    "09": {}
  }
*/

const r1 = _.mapValues(flatGroupMap, (value, key) => {
  return {
    accuracyList: [],
    group_type: undefined
  }
})

fs.writeFileSync(path.join(__dirname, 'json/​Steps-03.json'), JSON.stringify(r1, null, 2), 'utf8')
/*
{
  "TWO_ASCENDING_GROUPS": {
    "accuracyList": []
  },
  "TWO_ODD_EVEN_GROUPS": {
    "accuracyList": []
  },
  "TWO_PRIME_GROUPS": {
    "accuracyList": []
  },
}
*/

groupArray.forEach((item) => {
  const key = item.group_name
  r1[key].group_type = item.group_type
  r1[key].accuracyList = allValues.map((item, index) => {
    if (index === 0) {
      return 1
    } else {
      // index 从 1 开始
      const prevNumber = allValues[index - 1].number
      const prevIndex = numberGroupMap[prevNumber][key]
      const prevGroup = flatGroupMap[key][prevIndex]
      return prevGroup.map((item) => item.toString().padStart(2, '0')).includes(item.number.toString().padStart(2, '0'))
        ? 0
        : 1
    }
  })
})

// -------------------------------------------------------------------------------

// fs.writeFileSync(path.join(__dirname, 'json/​Steps-04.json'), JSON.stringify(r1, null, 2), 'utf8')

/*
{
  "TWO_ASCENDING_GROUPS": {
    "accuracyList": [1, 0, 1, 1, 0],
    "group_type": "two"
  },
  {
    "TWO_ODD_EVEN_GROUPS": {
    "accuracyList": [1, 0, 1, 1, 0],
    "group_type": "two"
  },
}
*/

console.time('计算结束')

// 优化后的筛选排序逻辑（优先级：当前连续错误 → 低准确率 → 高频错误）
const handleGroupPriorityEngine = require('./algorithms/handleGroupPriorityEngine.js')
// 嵌套分组排序
const handleProcessExerciseGroups = require('./algorithms/handleProcessExerciseGroups.js')
// 优化后的筛选排序逻辑（优先级：当前连续错误 → 低准确率 → 高频错误）
const handleOptimizeGroups = require('./algorithms/handleOptimizeGroups.js')

// 调试方法
const handleCalcGroups = require('./algorithms/handleCalcGroups.js')

// 过滤
const handleFilterGroups = require('./algorithms/handleFilterGroups.js')
// 排序
const handleOrderGroups = require('./algorithms/handleOrderGroups.js')
// 选号
const getLucky = require(path.join(HELPERS_DIR, 'getLucky.js'))

// todo write file
//*

const data = allValues.map((item, index) => {
  if (index < 2) {
    return {
      ...item,
      kill_array: [],
      lucky_array: []
    }
  } else {
    const currentGroupArray = _.chain(r1)
      .mapValues((value, key) => {
        const currentAccuracyList = value.accuracyList.slice(0, index + 1)
        // 计算准确率
        const stats = calcAccuracySummary(currentAccuracyList)
        return {
          groupName: key,
          groupType: value.group_type,
          accuracy_array: currentAccuracyList,
          stats
        }
      })
      .values()
      // .filter((item) => {
      //   const rateMap = {
      //     two: 1 - 2 / 49,
      //     three: 1 - 3 / 49,
      //     four: 1 - 4 / 49,
      //     five: 1 - 5 / 49,
      //     six: 1 - 6 / 49,
      //     seven: 1 - 7 / 49,
      //     eight: 1 - 8 / 49,
      //     ten: 1 - 10 / 49,
      //     twelve: 1 - 12 / 49,
      //     sixteen: 1 - 16 / 49
      //   }
      //   const theoryAccuracyRate = rateMap[item.groupType]
      //   // return item.stats.accuracyRate >= theoryAccuracyRate
      //   return item.stats.accuracyRate < theoryAccuracyRate && item.stats.accuracyRate >= (theoryAccuracyRate - 0.1)
      // })
      .value()

    // 过滤
    const filteredGroups = handleFilterGroups(currentGroupArray)
    // 排序
    const orderedGroups = handleOrderGroups(filteredGroups)

    if (index === 99) {
      fs.writeFileSync(
        path.join(__dirname, 'json/​Steps-05-currentGroupArray.json'),
        JSON.stringify(currentGroupArray, null, 2),
        'utf8'
      )
      console.log('​Steps-05 currentGroupArray 长度：', currentGroupArray.length)

      /*
        [
          {
              "groupName": "SIXTEEN_RANGE_00006000_GROUPS",
              "groupType": "sixteen",
              "accuracy_array": [1, 1, 0, 0],
              "stats": {
                "correctCount": 62,
                "incorrectCount": 38,
                "accuracyRate": 0.62,
                "maxConsecutiveCorrect": 7,
                "maxConsecutiveIncorrect": 3,
                "consecutiveCorrectSegments": 27,
                "consecutiveIncorrectSegments": 26,
                "avgConsecutiveCorrect": 2.2962962962962963,
                "avgConsecutiveIncorrect": 1.4615384615384615,
                "currentConsecutiveCorrect": 2,
                "currentConsecutiveIncorrect": 0
              }
            }
        ]
      */
      fs.writeFileSync(
        path.join(__dirname, 'json/​Steps-06-filteredGroups.json'),
        JSON.stringify(filteredGroups, null, 2),
        'utf8'
      )
      console.log('​Steps-06 filteredGroups 长度：', filteredGroups.length)

      fs.writeFileSync(
        path.join(__dirname, 'json/​Steps-07-orderedGroups.json'),
        JSON.stringify(orderedGroups, null, 2),
        'utf8'
      )
      console.log('​Steps-07 orderedGroups 长度：', orderedGroups.length)
    }

    // 选号
    const { lucky_array, kill_array, kill_group_names } = getLucky(orderedGroups, item, numberGroupMap, flatGroupMap)

    if (lucky_array.length < 32) {
      return {
        ...item,
        lucky_array: [],
        kill_array: [],
        kill_group_names
      }
    } else {
      return {
        ...item,
        lucky_array,
        kill_array,
        kill_group_names
      }
    }
  }
})

fs.writeFileSync(path.join(__dirname, 'json/​Steps-08-data.json'), JSON.stringify(data, null, 2), 'utf8')

/**
 * 滑动窗口遍历方法
 * @param {Object[]} arr - 输入的数组对象
 * @param {number} windowSize - 滑动窗口的大小
 */
function slidingWindowTraversal(arr, windowSize) {
  const result = []

  // 滑动窗口遍历数组
  for (let i = 0; i <= arr.length - windowSize; i++) {
    console.log(i)
    // 截取长度为 windowSize 的子数组
    const window = arr.slice(i, i + windowSize)
    result.push(window)
    console.log(window) // 可以查看每个窗口的内容
  }

  return result // 返回所有窗口的数组
}

const allList = data.map((item, index) => {
  if (index < 3) {
    return {
      ...item,
      accuracy: 1
    }
  } else {
    const prev = data[index - 1]

    if (prev.lucky_array.length) {
      return {
        ...item,
        accuracy: prev.lucky_array
          .map((item) => item.toString().padStart(2, '0'))
          .includes(item.number.toString().padStart(2, '0'))
          ? 1
          : 0
      }
    } else {
      return {
        ...item,
        accuracy: undefined
      }
    }
  }
})

fs.writeFileSync(path.join(__dirname, 'json/​Steps-09-allList.json'), JSON.stringify(allList, null, 2), 'utf8')

// eslint-disable-next-line spaced-comment
//*/

// todo read file
//*

fs.readFile(path.join(__dirname, 'json/​Steps-09-allList.json'), 'utf8', (err, jsonString) => {
  if (err) {
    console.error('读取文件失败:', err)
    return
  }
  try {
    const data = JSON.parse(jsonString)
    const accuracyList = data.filter((item) => item.accuracy === 1 || item.accuracy === 0).map((item) => item.accuracy)
    const accuracySummary = calcAccuracySummary(accuracyList)
    // 打印中文
    Object.entries(ACCURACY_SUMMARY_CN_MAP).forEach(([key, value]) => {
      console.log(`${value}: ${accuracySummary[key]}`)
    })

    console.timeEnd('计算结束')
  } catch (parseErr) {
    console.error('解析 JSON 失败:', parseErr)
  }
})

// eslint-disable-next-line spaced-comment
//*/
